<template>
  <div class="container">
    <el-form ref="form" :model="form" :rules="rules" label-width="210px">
      <el-form-item label="邮箱配置" prop="code">
        <el-select v-model="form.code" placeholder="请填写邮箱配置" clearable>
          <el-option
              v-for="item in mailConfigList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱模板" prop="tplId">
        <el-select v-model="form.tplId" placeholder="请填写邮箱模板" clearable @change="handleMailTplChange">
          <el-option
              v-for="item in mailTplList"
              :key="item.id"
              :label="item.name"
              :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主题" prop="subject">
        <el-input
            v-model="form.subject"
            placeholder="请填写主题"
            clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
            size="small"
            v-model="form.content"
            placeholder="请填写内容"
            type="textarea"
            :autosize="{ minRows: 50, maxRows: 50 }"
            show-word-limit
            maxlength="999"
        ></el-input>
      </el-form-item>
      <el-form-item
          v-for="(item, index) in form.tos"
          :key="index"
          :label="index === 0 ? `收件人` : ''"
          :prop="`tos[${index}]`"
          :rules="rules.tos"
      >
        <el-input
            v-model="form.tos[index]"
            :style="{ width: '300px', marginRight: '10px' }"
            placeholder="请填写收件人"
            clearable
        ></el-input>
        <el-button
            v-if="index !== 0"
            type="danger"
            icon="el-icon-delete"
            circle
            size="small"
            @click="bindRemove('tos', index)"
        ></el-button>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            size="small"
            @click="bindAdd('tos')"
        >新增收件人
        </el-button>
      </el-form-item>
      <el-form-item
          v-for="(item, index) in form.ccs"
          :key="index"
          :label="index === 0 ? `抄送人` : ''"
          :prop="`ccs[${index}]`"
          :rules="rules.ccs"
      >
        <el-input
            v-model="form.ccs[index]"
            :style="{ width: '300px', marginRight: '10px' }"
            placeholder="请填写抄送人"
            clearable
        ></el-input>
        <el-button
            v-if="index !== 0"
            type="danger"
            icon="el-icon-delete"
            circle
            size="small"
            @click="bindRemove('ccs', index)"
        ></el-button>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            size="small"
            @click="bindAdd('ccs')"
        >新增抄送人
        </el-button>
      </el-form-item>
      <el-form-item
          v-for="(item, index) in form.bccs"
          :key="index"
          :label="index === 0 ? `密送人` : ''"
          :prop="`bccs[${index}]`"
          :rules="rules.bccs"
      >
        <el-input
            v-model="form.bccs[index]"
            :style="{ width: '300px', marginRight: '10px' }"
            placeholder="请填写密送人"
            clearable
        ></el-input>
        <el-button
            v-if="index !== 0"
            type="danger"
            icon="el-icon-delete"
            circle
            size="small"
            @click="bindRemove('bccs', index)"
        ></el-button>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            size="small"
            @click="bindAdd('bccs')"
        >新增密送人
        </el-button>
      </el-form-item>
      <el-form-item label="附件" prop="attachments">
        <input class="upload_bp" type="file" multiple placeholder="file" @change="handleFileUpload"/>
        <ul class="upload-list">
          <li v-for="(file, index) in form.attachments" class="upload-list-li">
            <a class="upload-list-li-name"><i class="fa fa-file-text-o" aria-hidden="true"></i>{{ file.name }}</a>
            <label class="upload-list-li-label" @click="deleteFile(index, file.name)">
              <i class="el-icon-close"></i>
            </label>
          </li>
        </ul>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="sendMail">发送</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {mailSendApi} from "../../api/setup/mail";
import {mailConfigListEnabledApi} from "../../api/setup/mailConfig";
import {mailTplListEnabledApi} from "../../api/setup/mailTpl";
import {deepCopy} from "@/utils";

const obj = {
  code: "",
  subject: "",
  content: "",
  tos: [""],
  ccs: [""],
  bccs: [""],
  attachments: []
};
export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!value) {
        return callback(new Error("收件人不能为空"));
      } else {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("请填写正确的邮箱格式"));
        }
      }
    };
    return {
      form: deepCopy(obj),
      mailConfigList: [],
      mailTplList: [],
      rules: {
        code: [
          {required: true, message: "请填写邮箱配置", trigger: "change"},
        ],
        subject: [
          {required: true, message: "请填写主题", trigger: "change"},
          {max: 50, message: "长度不能超过50个字符", trigger: "change"},
        ],
        content: [
          {required: true, message: "请填写内容", trigger: "change"},
          {max: 999, message: "长度不能超过999个字符", trigger: "change"},
        ],
        tos: [
          {required: true, validator: checkEmail, trigger: "change"},
          {max: 50, message: "长度不能超过50个字符", trigger: "change"},
        ],
        ccs: [
          {max: 50, message: "长度不能超过50个字符", trigger: "change"},
        ],
        bccs: [
          {max: 50, message: "长度不能超过50个字符", trigger: "change"},
        ]
      },
    };
  },
  created() {
    this.getMailConfigList();
    this.getMailTplList();
  },
  methods: {
    getMailConfigList() {
      mailConfigListEnabledApi().then((res) => {
        this.mailConfigList = res?.bizData;
      });
    },
    getMailTplList() {
      mailTplListEnabledApi().then((res) => {
        this.mailTplList = res?.bizData;
      });
    },
    handleMailTplChange(val) {
      this.form.subject = val.name;
      this.form.content = val.templateContent;
    },
    handleFileUpload(event) {
      const files = event.target.files;
      for (let i = 0; i < files.length; i++) {
        this.form.attachments.push(files[i]);
      }
    },
    deleteFile(i, name) {
      this.form.attachments.splice(i, 1);
    },
    // 发送
    sendMail() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = new FormData();
          formData.set("code", this.form.code);
          formData.set("subject", this.form.subject);
          formData.set("content", this.form.content);
          if (this.form.tos.length > 0) {
            this.form.tos.forEach((item) => {
              if (item != '') {
                formData.append('tos', item);
              }
            });
          }
          if (this.form.ccs.length > 0) {
            this.form.ccs.forEach((item) => {
              if (item != '') {
                formData.append('ccs', item);
              }
            });
          }
          if (this.form.bccs.length > 0) {
            this.form.bccs.forEach((item) => {
              if (item != '') {
                formData.append('bccs', item);
              }
            });
          }
          if (this.form.attachments.length > 0) {
            this.form.attachments.forEach((item) => {
              if (item != '') {
                formData.append('attachments', item);
              }
            });
          }
          mailSendApi(formData).then(() => {
            const tips = `邮件发送成功`;
            this.$message.success(tips);
            if (this.$refs.form != undefined) {
              this.$refs['form'].resetFields();
            }
          });
        } else {
          return false;
        }
      });
    },
    // 动态新增行
    bindAdd(key) {
      this.form[key].push("");
    },
    // 动态删除行
    bindRemove(key, index) {
      this.form[key].splice(index, 1);
    },
  }
};
</script>

<style scoped>
.upload-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.upload-list-li {
  position: relative;
  margin-top: 5px;
  line-height: 1.8
}

.upload-list-li:hover {
  background-color: #f5f7fa;
}

.upload-list-li-name {
  position: relative;
  margin-right: 40px;
  display: block;
}

.fa-file-text-o {
  margin-right: 7px;
}

.upload-list-li-label {
  position: absolute;
  right: 25px;
  top: 0;
}

.upload-list-li-label .el-icon-close {
  margin: 0 10px;
  font-size: 20px;
  color: red;
}
</style>
